package com.qf.leadnewswemedia.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.leadnewswemedia.mapper.WmUserMapper;
import com.qf.leadnewswemedia.service.WmUserService;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import com.qf.qfleadnewsmodel.user.pojos.ApUser;
import com.qf.qfleadnewsmodel.wemedia.dtos.LoginDto;
import com.qf.qfleadnewsmodel.wemedia.pojos.WmUser;
import com.qf.qfleadnewsutils.commons.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {

        String name = loginDto.getName();
        String password = loginDto.getPassword();

        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据phone查询user对象
        LambdaQueryWrapper<WmUser> qw = Wrappers.lambdaQuery(WmUser.class).eq(WmUser::getName, name);
        WmUser wmUser = baseMapper.selectOne(qw);

        //判断是否存在
        if (wmUser == null){
            //不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PHONE_ERROR);
        }else{
            //确保状态是正常可用
            Integer status = wmUser.getStatus();

            if (status != 9){
                //账号不可用
                return ResponseResult.errorResult(AppHttpCodeEnum.ACCOUNT_NOT_ENABLE);
            }

            //存在 -- 将页面传递的密码+salt进行md5运算，将得到的密文和数据库的密文比对
            String salt = wmUser.getSalt();
            //页面传递过来的明文密码加盐后进行md5运算
            String pwdMd5 = MD5Utils.encodeHexString((password + salt).getBytes(StandardCharsets.UTF_8));
            pwdMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));

            if (!pwdMd5.equals(wmUser.getPassword())){
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //正确 -- 成功 （返回token + 用户信息）
            HashMap map = new HashMap();
            String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
            map.put("token",token);

            //对敏感信息进行脱敏处理
            wmUser.setPassword("");
            wmUser.setSalt("");

            map.put("user",wmUser);

            return ResponseResult.okResult(map);
        }
    }
}
